﻿<template>
    <el-dialog :title="!dataForm.id ? '新建' : '编辑'" :close-on-click-modal="false" :visible.sync="visible" class="SHZY-dialog SHZY-dialog_center" lock-scroll width="1200px">
        <el-row :gutter="15" class="">
            <el-form ref="elForm" :model="dataForm" size="small" label-width="110px" label-position="right" :rules="rules">
                <el-col :span="24">
                    <el-form-item label="⼯艺路线编码" prop="enCode">
                        <el-input v-model="dataForm.enCode" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="⼯艺路线名称" prop="fullName">
                        <el-input v-model="dataForm.fullName" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="说明描述" prop="desc">
                        <el-input v-model="dataForm.desc" placeholder="请输入" show-word-limit :style="{ width: '100%' }" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="有效标志" prop="enabledMark">
                        <el-switch v-model="dataForm.enabledMark" :active-value="1" :inactive-value="0"></el-switch>
                    </el-form-item>
                    <div class="SHZY-common-title">
                        <h2>物料</h2>
                    </div>
                </el-col>
            </el-form>
            <el-table :data="dataForm.materiallist" size="mini">
                <el-table-column type="index" width="50" label="序号" align="center"/>
                <el-table-column prop="materialId" label="选择物料">
                    <template slot="header">
                        <span class="required-sign">*</span>选择物料
                    </template>
                    <template slot-scope="scope">
                        <SHZY-select :key="scope.$index" :list="materialOptions" v-model:bindValue="scope.row.id" label="code" value="id" @change="getMaterialdetaildata(scope)" placeholder="物料"></SHZY-select>
                    </template>
                </el-table-column>
                <el-table-column prop="Code" label="物料编码" v-if="false">
                    <template slot="header">
                        <span class="required-sign">*</span>物料编码
                    </template>
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.code" :style="{ width: '100%' }" placeholder="请输入" clearable required disabled></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="Name" label="物料名称">
                    <template slot="header">
                        <span class="required-sign">*</span>物料名称
                    </template>
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.name" :style="{ width: '100%' }" placeholder="请输入" clearable required disabled></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="Unit" label="计量单位">
                    <template slot="header">
                        <span class="required-sign">*</span>计量单位
                    </template>
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.unit" :style="{ width: '100%' }" placeholder="请输入" clearable required disabled></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="EnabledMark" label="有效标志">
                    <template slot="header"> 有效标志 </template>
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.enabledMark" required :active-value="1" :inactive-value="0"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="50">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" class="SHZY-table-delBtn" @click="handleDelmaterialList(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="table-actions" @click="addEntityList()">
                <el-button type="text" icon="el-icon-plus">新增</el-button>
            </div>
            <div class="SHZY-common-title">
                <h2>工序</h2>
            </div>
            <el-table v-loading="listLoading" :data="dataForm.modelinglist" size="mini" ref="dragTable" :row-key="row => row.index">
                <el-table-column align="center" label="拖动" width="50">
                    <template>
                        <i class="drag-handler icon-ym icon-ym-darg" style="cursor: move;font-size:20px" title='点击拖动' />
                    </template>
                </el-table-column>
                <el-table-column type="index" width="50" label="序号" align="center" />
                <el-table-column prop="detailId" label="选择工序">
                    <template slot="header">
                        <span class="required-sign">*</span>选择工序
                    </template>
                    <template slot-scope="scope">
                        <SHZY-select :key="scope.$index" :list="modelingOptions" v-model:bindValue="scope.row.id" label="fullName" value="id" @change="getmodelingdetaildata(scope)" placeholder="工序"></SHZY-select>
                    </template>
                </el-table-column>
                <el-table-column prop="enCode" label="工序编码">
                    <template slot="header">
                        <span class="required-sign">*</span>工序编码
                    </template>
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.enCode" :style="{ width: '100%' }" placeholder="请输入" clearable required disabled>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="fullName" label="工序名称">
                    <template slot="header">
                        <span class="required-sign">*</span>工序名称
                    </template>
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.fullName" :style="{ width: '100%' }" placeholder="请输入" clearable required disabled>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="stationCode" label="默认工位">
                    <template slot="header">
                        默认工位
                    </template>
                    <template slot-scope="scope">
                        <SHZY-select :key="scope.$index" :list="stationOptions" v-model:bindValue="scope.row.stationCode" label="FullName" value="stationCode" placeholder="工位" isConcat concatSymbol=" / ">
                        </SHZY-select>
                    </template>
                </el-table-column>
                <el-table-column prop="pieceRate" label="计价单价">
                    <template slot="header">
                        计价单价
                    </template>
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.pieceRate" :style="{ width: '100%' }" placeholder="数字文本" :step="1" :min="0">
                        </el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="EnabledMark" label="有效标志">
                    <template slot="header">
                        有效标志
                    </template>
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.enabledMark" required :active-value="1" :inactive-value="0">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="50">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" class="SHZY-table-delBtn" @click="handleDelmodelingList(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="table-actions" @click="addmodelingList()">
                <el-button type="text" icon="el-icon-plus">新增</el-button>
            </div>
        </el-row>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancelForm()">取 消</el-button>
            <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import Sortable from 'sortablejs'
import ApiArt from "@/api/common/artroute";
import Enumerable from "linq";
import is from "is_js";
import { getMaterialAll,GetInfoForArt } from "@/api/common/material";
import { getModelingAll,GetInfoFy } from "@/api/common/modeling";
export default {
    components: {},
    props: [],
    data() {
        return {
            btnLoading: false,
            loading: false,
            visible: false,
            materialOptions: [],
            modelingOptions: [],
            stationOptions: [],
            sortable: null,
            listLoading: false,
            dataForm: {
                id: "",
                enCode: undefined,
                fullName: undefined,
                desc: undefined,
                enabledMark: 1,
                materiallist: [],
                modelinglist: []
            },
            rules: {
                enCode: [
                    {
                        required: true,
                        message: "请输入⼯艺路线编码",
                        trigger: '"blur"'
                    },
                    {
                        pattern: /^(?!\s+$).+/,
                        message: "请输入⼯艺路线编码",
                        trigger: "blur"
                    }
                ],
                fullName: [
                    {
                        required: true,
                        message: "请输入⼯艺路线名称",
                        trigger: '"blur"'
                    },
                    {
                        pattern: /^(?!\s+$).+/,
                        message: "请输入⼯艺路线名称",
                        trigger: "blur"
                    }
                ]
            }
        };
    },
    computed: {},
    watch: {},
    created() {
        this.getMaterialList();
        this.getmodelingList();
        this.getStationAll();
    },
    mounted() {},
    methods: {
        checkRule() {
            for (let i = 0; i < this.dataForm.modelinglist.length; i++) {
                const fe = this.dataForm.modelinglist[i];
                fe.isOk = true;
                if (is.undefined(fe.enCode)) {
                    fe.enCodeDesc = "请选择工序，工序信息不能为空！";
                    fe.isOk = false;
                    this.$message.error(fe.enCodeDesc);
                }
            }

            for (let i = 0; i < this.dataForm.materiallist.length; i++) {
                const fe = this.dataForm.materiallist[i];
                fe.isOk = true;
                if (is.undefined(fe.code)) {
                    fe.codeDesc = "请选择物料，物料信息不能为空！";
                    fe.isOk = false;
                    this.$message.error(fe.codeDesc);
                }
            }

            let isOk = Enumerable.from(this.dataForm.modelinglist).all(
                a => a.isOk
            );

            let isOk_ = Enumerable.from(this.dataForm.materiallist).all(
                a => a.isOk
            );

            if (isOk && isOk_) {
                return true;
            }
            return false;
        },
        goBack() {
            this.$emit("refresh");
        },
        createList() {
            this.dataForm.materiallist = [];
            this.dataForm.modelinglist = [];
        },
        async init(id) {
            this.dataForm.id = id || 0;
            this.visible = true;
            this.listLoading = true;
            this.$nextTick(async () => {
                this.$refs["elForm"].resetFields();
                if (this.dataForm.id) {
                    try {
                        const [
                            routeRes,
                            materialRes,
                            detailRes
                        ] = await Promise.all([
                        ApiArt.getInfo(this.dataForm.id),
                        ApiArt.getMaterialInfo(this.dataForm.id),
                        ApiArt.getDetailInfo(this.dataForm.id)
                        ]);
                        this.dataForm = routeRes.data;
                        this.dataForm.materiallist = materialRes.data;
                        this.dataForm.modelinglist = detailRes.data.map((o, i) => ({ index: i, ...o }));
                        this.listLoading = false;
                    } catch (error) {
                        // 处理API错误
                        console.error(error);
                    }
                } else {
                    this.listLoading = false
                    this.dataForm.modelinglist = []
                }
            });
            this.$nextTick(() => {
                this.setSort()
            })
        },
        setSort() {
            const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
            this.sortable = Sortable.create(el, {
                sort: true,
                ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
                setData: function (dataTransfer) {
                    // to avoid Firefox bug
                    // Detail see : https://github.com/RubaXa/Sortable/issues/1012
                    dataTransfer.setData('Text', '')
                },
                onEnd: evt => {
                    const targetRow = this.dataForm.modelinglist.splice(evt.oldIndex, 1)[0]
                    this.dataForm.modelinglist.splice(evt.newIndex, 0, targetRow)
                },
                handle: '.drag-handler',
            })
        },
        dataFormSubmit() {
            let isOk = this.checkRule();
            console.log(isOk);
            if (!isOk) {
                return;
            } else {
                this.$refs["elForm"].validate(valid => {
                    if (valid) {
                        this.btnLoading = true;
                        if (!this.dataForm.id) {
                            ApiArt.create(this.dataForm)
                                .then(res => {
                                    this.$message({
                                        message: res.msg,
                                        type: "success",
                                        duration: 1000,
                                        onClose: () => {
                                            (this.visible = false),
                                                this.$emit("refresh", true);
                                        }
                                    });
                                })
                                .catch(res => {
                                    this.btnLoading = false;
                                });
                        } else {
                            ApiArt.update(this.dataForm)
                                .then(res => {
                                    this.$message({
                                        message: res.msg,
                                        type: "success",
                                        duration: 1000,
                                        onClose: () => {
                                            this.visible = false;
                                            this.$emit("refresh", true);
                                        }
                                    });
                                })
                                .catch(res => {
                                    this.btnLoading = false;
                                });
                        }
                    }
                });
            }
        },
        addEntityList() {
            let item = {
                id: undefined,
                materialId: undefined,
                code: undefined,
                name: undefined,
                unit: undefined,
                codeDesc: undefined,
                isOk: false,
                enabledMark: 1
            };
            this.dataForm.materiallist.push(item);
        },
        addmodelingList() {
            let index = this.dataForm.modelinglist.length;
            let item = {
                id: undefined,
                detailId: undefined,
                enCode: undefined,
                fullName: undefined,
                stationCode: undefined,
                pieceRate: undefined,
                enCodeDesc: undefined,
                isOk: false,
                enabledMark: 1,
                index: index,
            };
            this.dataForm.modelinglist.push(item);
        },
        handleDelmaterialList(index) {
            this.dataForm.materiallist.splice(index, 1);
            console.log(this.dataForm.materiallist);
        },
        handleDelmodelingList(index) {
            this.dataForm.modelinglist.splice(index, 1);
        },
        getMaterialList() {
            getMaterialAll().then(res => {
                this.materialOptions = res.data.list;
            });
        },
        getMaterialdetaildata(scope) {
            GetInfoForArt(scope.row.id).then(res => {
                console.log(this.dataForm.materiallist)
                if(this.dataForm.materiallist.length==1){
                       this.$set(this.dataForm.materiallist, scope.$index, res.data);
                       this.dataForm.materiallist[scope.$index].enabledMark = 1;
                    }
                for(let i=0;i<this.dataForm.materiallist.length-1;i++){
                    if(this.dataForm.materiallist[i].id==res.data.id){
                        this.$message.error(res.data.code+'物料已存在');
                        this.$set(this.dataForm.materiallist, scope.$index, res.data);
                        this.dataForm.materiallist[scope.$index].enabledMark = 1;
                        this.dataForm.materiallist.splice(i,1);
                        break;
                    }else{
                        this.$set(this.dataForm.materiallist, scope.$index, res.data);
                        this.dataForm.materiallist[scope.$index].enabledMark = 1;
                       
                    }
                }
                
            });
        },
        getmodelingList() {
            getModelingAll().then(res => {
                this.modelingOptions = res.data.list;
            });
        },
        getmodelingdetaildata(scope) {
            GetInfoFy(scope.row.id).then(res => {
                if(this.dataForm.modelinglist.length==1){
                       this.$set(this.dataForm.modelinglist, scope.$index, res.data);
                       this.dataForm.modelinglist[scope.$index].enabledMark = 1;
                    }
                for(let i=0;i<this.dataForm.modelinglist.length-1;i++){
                    if(this.dataForm.modelinglist[i].id!=res.data.id){
                       this.$set(this.dataForm.modelinglist, scope.$index, res.data);
                       this.dataForm.modelinglist[scope.$index].enabledMark = 1;
                    }else{
                        this.$message.error(res.data.fullName+'工序已存在');
                        this.$set(this.dataForm.modelinglist, scope.$index, res.data);
                        this.dataForm.modelinglist[scope.$index].enabledMark = 1;
                        this.dataForm.modelinglist.splice(i,1);
                        //this.dataForm.modelinglist.splice(this.dataForm.modelinglist.length-1,1);
                        break;
                    }
                }
                // this.$set(this.dataForm.modelinglist, scope.$index, res.data);
                // this.dataForm.modelinglist[scope.$index].enabledMark = 1;
            });
        },
        getStationAll() {
            ApiArt.getStationAlldata().then(res => {
                this.stationOptions = res.data;
            });
        },
        cancelForm() {
            this.dataForm.materiallist = [];
            this.dataForm.modelinglist = [];
            this.visible = false;
        }
    }
};
</script>
